package com.fc.utils;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * Excel 工具类
 */
@Slf4j
@RequiredArgsConstructor
@Component
public class ExcelUtil {

    // 默认导出目录（可自定义）
    @Value("${vehicle.export}")
    private  String defaultExportDir;

    /**
     * 导入整张表
     */
    public <T> List<T> importExcel(MultipartFile file, Class<T> clazz) throws IOException {
        if (file.isEmpty()) {
            throw new IllegalArgumentException("上传的文件为空");
        }

        return EasyExcel.read(file.getInputStream())
                .head(clazz)
                .sheet()
                .doReadSync();
    }

    /**
     * 导出单个 Sheet
     */
    public Path exportSingle(String baseName, Sheet<?> sheet) throws IOException {
        String filepath = generateUniqueFileName(baseName);
        EasyExcel.write(filepath, sheet.getClazz()).sheet(sheet.getName()).doWrite(sheet.getData());
        return Path.of(filepath);
    }

    /**
     * 导出多个 Sheet
     */
    public Path exportMulti(String baseName, List<Sheet<?>> sheets) throws IOException {
        String filepath = generateUniqueFileName(baseName);

        // 创建 ExcelWriter
        ExcelWriter writer = EasyExcel.write(filepath).build();
        // 写入每个 sheet
        for (int i = 0; i < sheets.size(); i++) {
            Sheet<?> sheet = sheets.get(i);
            WriteSheet writeSheet = EasyExcel.writerSheet(i, sheet.getName())
                    .head(sheet.getClazz())
                    .build();
            writer.write(sheet.getData(), writeSheet);
        }
        // 手动关闭 ExcelWriter
        writer.finish();
        return Path.of(filepath);
    }

    /**
     * 生成带时间戳的唯一文件名（避免覆盖）
     */
    private String generateUniqueFileName(String baseName) throws IOException {
        // 确保目录存在
        File dir = new File(defaultExportDir);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        // 使用时间戳和随机数生成唯一文件名
        String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
        String randomSuffix = java.util.UUID.randomUUID().toString().substring(0, 4); // 随机后缀，避免极小概率的冲突

        return String.format("%s%s_%s_%s.xlsx", defaultExportDir, baseName, timestamp, randomSuffix);
    }

    /**
     * Sheet 数据封装类
     */
    @AllArgsConstructor
    @Data
    public static class Sheet<T> {
        private final String name;
        private final List<T> data;
        private final Class<T> clazz;
    }
}